<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/6/13
 * Time: 18:05
 */

namespace app\common\services;


use app\common\util\DateTimeUtil;
use app\common\util\weixin\Request;
use app\common\util\weixin\Dispatcher;
use app\common\util\weixin\Response;
use app\common\util\weixin\UserManager;
use think\Config;
use think\Exception;

class WeixinService
{
    public function __construct()
    {
    }

    public function checkSignature()
    {
        return Request::checkSignature(Config::get('weixin.ccnn_token'));
    }

    public function dispatch()
    {
        if ($this->checkSignature()) {
            $dispatcher = Dispatcher::instance();
            $dispatcher->addEventListener('text', [$this, 'onTextMsg']);
            $dispatcher->addEventListener('event.subscribe', [$this, 'subscribe']);
            $dispatcher->addEventListener('event.scan', [$this, 'scan']);
            $dispatcher->addEventListener('event.unsubscribe', [$this, 'unsubscribe']);
            $dispatcher->dispatch();
        }
    }

    /**
     * @param $request Request
     */
    public function onTextMsg($request)
    {
        try {
            $content = $request->content;
            if (!empty($content)) {
                $openid = $request->fromusername;
                $replies = M('autoreply')->where(['keywords' => ['like', '%' . $content . '%']])->select();
                $answer = '';
                if (!empty($replies)) {
                    foreach ($replies as $reply) {
                        $op = intval($reply['op']);
                        $keywords = trim($reply['keywords']);
                        if ($op == 0) {
                            if ($keywords == $content) {
                                $answer = $reply['content'];
                                break;
                            }
                        } elseif ($op == 1) {
                            $answer = $reply['content'];
                        }
                    }
                }
                if (!empty($answer)) {
                    echo Response::text($openid, $request->tousername, $answer);
                }
                $dialogDb = M('wx_dialog');
                $messageDb = M('wx_dialog_message');
                $dialog_id = $dialogDb->where(['openid' => $openid])->getField('id');
                if (empty($dialog_id)) {
                    $dialog_id = $dialogDb->add([
                        'openid' => $openid
                    ]);
                }
                $last_msg_id = $messageDb->add([
                    'dialog_id' => $dialog_id,
                    'content' => $content,
                    'create_time' => DateTimeUtil::now()
                ]);
                $dialogDb->where(['id' => $dialog_id])->setField('last_message_id', $last_msg_id);
            }
        } catch (Exception $e) {
            ccnn_log($e->getMessage());
        }
    }

    public function subscribe($request)
    {
        $content = '你好,欢迎关注深圳市广电公益基金服务号';
        $memberDb = M('member');
        $now = DateTimeUtil::now();
        $member_id = $memberDb->where(['openid' => $request->fromusername])->getField('id');
        if (empty($member_id)) {
            $userinfo = UserManager::getUserInfo($request->fromusername);
            $memberDb->add([
                'nickname' => $userinfo['nickname'],
                'avatar' => $userinfo['headimgurl'],
                'openid' => $request->fromusername,
                'create_time' => $now,
                'sex' => $userinfo['sex'],
                'subscribe' => 1,
                'subscribe_time' => $now
            ]);
        } else {
            $memberDb->where(['id' => $member_id])->save([
                'subscribe' => 1,
                'subscribe_time' => $now
            ]);
        }
        echo Response::text($request->fromusername, $request->tousername, $content);
    }

    public function unsubscribe($request)
    {
        $memberDb = M('member');
        if ($memberDb->where(['openid' => $request->fromusername])->count()) {
            $memberDb->where(['openid' => $request->fromusername])->save([
                'subscribe' => 0,
                'unsubscribe_time' => DateTimeUtil::now()
            ]);
        }
    }

    public function scan($request)
    {
    }



}